package com.mofofa.maozy.components.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.*
import androidx.core.content.ContextCompat
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.viewpager.widget.ViewPager
import com.mofofa.maozy.R
import com.mofofa.maozy.base.BaseDialogAction
import com.mofofa.maozy.databinding.DialogMaozyPermissionsBinding


class PermissionsHomeDialog : DialogFragment(), BaseDialogAction {

    companion object {

        /**
         * 判断所有权限是否完成
         */
        fun checkAllPermissionAgree(contxt: Context): Boolean {
            var agreeSms = false
            if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(
                    contxt,
                    android.Manifest.permission.READ_SMS
                )
            ) {
                agreeSms = true
            }

            var agreePhoneState = false
            if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(
                    contxt,
                    android.Manifest.permission.READ_PHONE_STATE
                )
            ) {
                agreePhoneState = true
            }

            return (agreeSms and agreePhoneState)
        }

        /**
         * 获取待申请的权限列表
         * */
        fun getPermissionList(context: Context): List<PermissionItem> {
            val permissionList = mutableListOf<PermissionItem>()
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                    context,
                    android.Manifest.permission.READ_SMS
                )
            ) {
                permissionList.add(PermissionItem(type = PermissionItem.TYPE_SMS))
            }
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                    context,
                    android.Manifest.permission.READ_PHONE_STATE
                )
            ) {
                permissionList.add(PermissionItem(type = PermissionItem.TYPE_PHONE_STATE))
            }
            if (permissionList.isNotEmpty()) {
                permissionList.add(0, PermissionItem(type = PermissionItem.TYPE_APP))
            }
            return permissionList
        }
    }

    //列表适配器
    private lateinit var mPermissionsAdapter: PermissionsAdapter

    //列表数据
    private val mPermissionList = mutableListOf<PermissionItem>()

    //布局句柄
    lateinit var mMaozyViewMaozyBinding: DialogMaozyPermissionsBinding

    /**
     * 点击回调
     *
     * @return Boolean 是否为短信
     */
    private var mStartRequestPermissionClickListener: (type: Int) -> Unit = { }

    /**
     * phone state权限点击拒绝回调
     *
     */
    private var mPhoneSateDenyClickListener: () -> Unit = {}

    /**
     * 所有权限点击同意回调
     *
     */
    private var mAllRequestPermissionAgreeListener: () -> Unit = {}


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mMaozyViewMaozyBinding =
            DialogMaozyPermissionsBinding.inflate(layoutInflater)

        return mMaozyViewMaozyBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initMaozySubviews()
        dialog?.setCancelable(false)
        dialog?.setCanceledOnTouchOutside(false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.Dialog)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onStart() {
        super.onStart()

        dialog?.window?.let {
            it.attributes.gravity = Gravity.CENTER
            it.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
//            it.setWindowAnimations(R.style.bottomDialogAnimation)
        }

        if (mPermissionList.size == 1) {
            mMaozyViewMaozyBinding.vPermissionPageDot1.visibility = View.VISIBLE

            mMaozyViewMaozyBinding.vPermissionPageDotEdge1.visibility = View.GONE
            mMaozyViewMaozyBinding.vPermissionPageDot2.visibility = View.GONE

            mMaozyViewMaozyBinding.vPermissionPageDotEdge2.visibility = View.GONE
            mMaozyViewMaozyBinding.vPermissionPageDot3.visibility = View.GONE

        } else if (mPermissionList.size == 2) {
            mMaozyViewMaozyBinding.vPermissionPageDot1.visibility = View.VISIBLE

            mMaozyViewMaozyBinding.vPermissionPageDotEdge1.visibility = View.VISIBLE
            mMaozyViewMaozyBinding.vPermissionPageDot2.visibility = View.VISIBLE

            mMaozyViewMaozyBinding.vPermissionPageDotEdge2.visibility = View.GONE
            mMaozyViewMaozyBinding.vPermissionPageDot3.visibility = View.GONE

        } else if (mPermissionList.size == 3) {
            mMaozyViewMaozyBinding.vPermissionPageDot1.visibility = View.VISIBLE

            mMaozyViewMaozyBinding.vPermissionPageDotEdge1.visibility = View.VISIBLE
            mMaozyViewMaozyBinding.vPermissionPageDot2.visibility = View.VISIBLE

            mMaozyViewMaozyBinding.vPermissionPageDotEdge2.visibility = View.VISIBLE
            mMaozyViewMaozyBinding.vPermissionPageDot3.visibility = View.VISIBLE

        } else {
            mMaozyViewMaozyBinding.vPermissionPageDot1.visibility = View.GONE

            mMaozyViewMaozyBinding.vPermissionPageDotEdge1.visibility = View.GONE
            mMaozyViewMaozyBinding.vPermissionPageDot2.visibility = View.GONE

            mMaozyViewMaozyBinding.vPermissionPageDotEdge2.visibility = View.GONE
            mMaozyViewMaozyBinding.vPermissionPageDot3.visibility = View.GONE
        }
    }

    override fun initMaozySubviews() {
        try {
            //初始化数据
//            mPermissionList.add(PermissionItem(type = PermissionItem.TYPE_APP))
//            mPermissionList.add(PermissionItem(type = PermissionItem.TYPE_SMS))
//            mPermissionList.add(PermissionItem(type = PermissionItem.TYPE_PHONE_STATE))

            //初始化适配器
            mPermissionsAdapter = PermissionsAdapter(requireContext(), mPermissionList)
            mPermissionsAdapter.setItemClickListener { action, permissionItem, position ->
                println("action: $action type: ${permissionItem.type}  position: $position")
                //如果是同意
                if (action == PermissionItem.RESULT_AGREE) {
                    if (permissionItem.type == PermissionItem.TYPE_APP) {
                        //如果是app list 直接展示下一个权限
                        setPermissionResult(PermissionItem.TYPE_APP, true)
                    } else {
                        mStartRequestPermissionClickListener.invoke(permissionItem.type)
                    }
                } else {
                    if (permissionItem.type == PermissionItem.TYPE_APP) {
                        mMaozyViewMaozyBinding.viewpagerDialogPermissions
                            .setCurrentItem(position + 1, true)
                    } else {
                        mPhoneSateDenyClickListener.invoke()
                    }
                }
            }

            mMaozyViewMaozyBinding.viewpagerDialogPermissions.adapter =
                mPermissionsAdapter

            mMaozyViewMaozyBinding.viewpagerDialogPermissions.pageMargin = 0
            mMaozyViewMaozyBinding.viewpagerDialogPermissions.offscreenPageLimit = 3
            mMaozyViewMaozyBinding.viewpagerDialogPermissions.addOnPageChangeListener(
                object : ViewPager.OnPageChangeListener {
                    override fun onPageScrolled(
                        position: Int,
                        positionOffset: Float,
                        positionOffsetPixels: Int
                    ) {
                    }

                    override fun onPageSelected(position: Int) {
                        //设置当前/总数

                        if (0 == position) {
                            mMaozyViewMaozyBinding.vPermissionPageDot1.setBackgroundResource(
                                R.drawable.maozy_permission_page_dot_yes
                            )
                            mMaozyViewMaozyBinding.vPermissionPageDot2.setBackgroundResource(
                                R.drawable.maozy_permission_page_dot_no
                            )
                            mMaozyViewMaozyBinding.vPermissionPageDot3.setBackgroundResource(
                                R.drawable.maozy_permission_page_dot_no
                            )

                        } else if (1 == position) {
                            mMaozyViewMaozyBinding.vPermissionPageDot1.setBackgroundResource(
                                R.drawable.maozy_permission_page_dot_no
                            )
                            mMaozyViewMaozyBinding.vPermissionPageDot2.setBackgroundResource(
                                R.drawable.maozy_permission_page_dot_yes
                            )
                            mMaozyViewMaozyBinding.vPermissionPageDot3.setBackgroundResource(
                                R.drawable.maozy_permission_page_dot_no
                            )

                        } else {
                            mMaozyViewMaozyBinding.vPermissionPageDot1.setBackgroundResource(
                                R.drawable.maozy_permission_page_dot_no
                            )
                            mMaozyViewMaozyBinding.vPermissionPageDot2.setBackgroundResource(
                                R.drawable.maozy_permission_page_dot_no
                            )
                            mMaozyViewMaozyBinding.vPermissionPageDot3.setBackgroundResource(
                                R.drawable.maozy_permission_page_dot_yes
                            )
                        }
                    }

                    override fun onPageScrollStateChanged(state: Int) {
                    }
                })

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun showMaozyWithMaozyUIMaozyTag(
        gTag: String,
        fragmentManager: FragmentManager
    ) {
    }

    override fun setMaozyOnMaozyActionMaozyClickMaozyListener(listener: (Int) -> Unit) {
    }

    /**
     * 设置数据源
     */
    fun setPermissionList(list: List<PermissionItem>) {
        mPermissionList.clear()
        mPermissionList.addAll(list)
    }

    /**
     * 更新视图
     */
    fun refresh() {
        mPermissionsAdapter.notifyDataSetChanged()
    }

    /**
     * 设置点击回调
     *
     * @param Int 类型
     * @param RevObjAiHomeDemo 值
     */
    fun setStartRequestPermissionClickListener(listener: (Int) -> Unit) {
        mStartRequestPermissionClickListener = listener
    }

    /**
     * 设置所有权限同意回调
     *
     * @param Int 类型
     * @param RevObjAiHomeDemo 值
     */
    fun setAllRequestPermissionAgreeListener(listener: () -> Unit) {
        mAllRequestPermissionAgreeListener = listener
    }

    /**
     * 设置点击回调
     *
     * @param Int 类型
     * @param RevObjAiHomeDemo 值
     */
    fun setPhoneSateDenyClickListener(listener: () -> Unit) {
        mPhoneSateDenyClickListener = listener
    }

    /** 设置权限操作结果 */
    fun setPermissionResult(type: Int, agree: Boolean) {
        mPermissionList.forEach { item ->
            if (item.type == type) {
                item.result = if (agree) PermissionItem.RESULT_AGREE else PermissionItem.RESULT_DENY
            }
        }
        //刷新页面
        mPermissionsAdapter.notifyDataSetChanged()

        val position = mMaozyViewMaozyBinding.viewpagerDialogPermissions.currentItem
        mMaozyViewMaozyBinding.viewpagerDialogPermissions.setCurrentItem(
            position + 1,
            true
        )

        //判断下设备权限是否完成
        val agreeAllPermissions = checkAllPermissionAgree(requireContext())
        println("=============agreeAllPermissions: $agreeAllPermissions")

        if (agreeAllPermissions) {
            mAllRequestPermissionAgreeListener.invoke()
            dismiss()
        }
    }
}